package com.idopartx.phonelightning.ui.home.smslightning

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.dotools.umlibrary.UMPostUtils
import com.idopartx.phonelightning.R
import com.idopartx.phonelightning.common.Constant
import com.idopartx.phonelightning.databinding.ActivitySmsLightingBinding
import com.idopartx.phonelightning.databinding.DialogExitBinding
import com.idopartx.phonelightning.entity.LightNightVo
import com.idopartx.phonelightning.entity.NotifyLightningCache
import com.idopartx.phonelightning.thread.LightningThread
import com.idopartx.phonelightning.ui.base.BaseActivity
import com.idopartx.phonelightning.utils.DialogUtil
import com.idopartx.phonelightning.viewmodel.NotifyLightingViewModel
import com.idopartx.phonelightning.widget.KBubbleSeekBar
import com.tencent.mmkv.MMKV
import com.wuhenzhizao.titlebar.widget.CommonTitleBar

/**
 * 短信闪光
 */
class SmsLightningActivity : BaseActivity<ActivitySmsLightingBinding>() {

    private val viewModel: NotifyLightingViewModel by lazy {
        ViewModelProvider(this).get(NotifyLightingViewModel::class.java)
    }

    private val smsLightningCache: NotifyLightningCache? by lazy {
        MMKV.defaultMMKV()
            .decodeParcelable(Constant.MMKV_SAVE_SMS_LIGHTNING, NotifyLightningCache::class.java)
    }

    private var thread: LightningThread? = null

    override fun initLayoutResId(): Int {
        return R.layout.activity_sms_lighting
    }

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel.lightNightLiveData.value =
            if (smsLightningCache?.lightNightList != null && smsLightningCache?.lightNightList!!.isNotEmpty()) smsLightningCache?.lightNightList else arrayListOf(
                LightNightVo(500, 500)
            )

        viewModel.periodLiveData.value = smsLightningCache?.showTimes ?: 2

        binding.tvTitle.text = "闪烁周期${viewModel.periodLiveData.value}"

        binding.viewModel = viewModel

        binding.viewTitleBar.setListener { v, action, _ ->
            when (action) {
                CommonTitleBar.ACTION_RIGHT_TEXT -> {

                    UMPostUtils.onEvent(this, "text_save_click")

                    if (v is TextView) {
                        saveData()
                    }
                }

                CommonTitleBar.ACTION_LEFT_BUTTON -> {
                    onBackPressedSupport()
                }
            }
        }

        binding.sbPeriod.setProgress((viewModel.periodLiveData.value ?: 2).toFloat())

        binding.sbLight.setProgress(
            (viewModel.lightNightLiveData.value?.get(0)?.light ?: 500).toFloat() / 10
        )
        binding.sbNight.setProgress(
            (viewModel.lightNightLiveData.value?.get(0)?.night ?: 500).toFloat() / 10
        )



        binding.sbPeriod.onProgressChangedListener =
            object : KBubbleSeekBar.OnProgressChangedListener {
                override fun onProgressChanged(
                    bubbleSeekBar: KBubbleSeekBar?,
                    progress: Int,
                    progressFloat: Float,
                    fromUser: Boolean
                ) {
                    binding.tvTitle.text = "闪烁周期${progress}"
                }

                override fun getProgressOnActionUp(
                    bubbleSeekBar: KBubbleSeekBar?,
                    progress: Int,
                    progressFloat: Float
                ) {
                }

                override fun getProgressOnFinally(
                    bubbleSeekBar: KBubbleSeekBar?,
                    progress: Int,
                    progressFloat: Float,
                    fromUser: Boolean
                ) {
                    binding.tvTitle.text = "闪烁周期${progress}"

                    viewModel.periodLiveData.value = progress
                    thread = null
                    thread?.stopThread()
                    thread = LightningThread(
                        applicationContext,
                        viewModel.lightNightLiveData.value,
                        viewModel.periodLiveData.value ?: 2
                    )
                    thread?.start()
                }
            }

        binding.sbLight.onProgressChangedListener =
            getOnProgressChangedListener("亮%dms", binding.tvLightNum)
        binding.tvLightNum.text = String.format("亮%dms", binding.sbLight.progress * 10)

        binding.sbNight.onProgressChangedListener =
            getOnProgressChangedListener("灭%dms", binding.tvNightNum)
        binding.tvNightNum.text = String.format("灭%dms", binding.sbNight.progress * 10)
    }


    private fun saveData() {
        val cache = NotifyLightningCache(
            viewModel.periodLiveData.value,
            viewModel.lightNightLiveData.value,
            viewModel.settingAllLiveData.value,
            null
        )
        MMKV.defaultMMKV().encode(Constant.MMKV_SAVE_SMS_LIGHTNING, cache)
        finish()
    }

    private fun checkEdit(): Boolean {
        if (smsLightningCache == null) {
            return false
        }
        if (smsLightningCache?.showTimes != viewModel.periodLiveData.value) {
            return false
        }

        if (smsLightningCache?.lightNightList != viewModel.lightNightLiveData.value) {
            return false
        }


        return true
    }

    override fun onBackPressedSupport() {
        if (checkEdit()) {
            finish()
            return
        }

        val dialogBinding = DataBindingUtil.inflate<DialogExitBinding>(
            LayoutInflater.from(this),
            R.layout.dialog_exit,
            null,
            false
        )
        val dialog = DialogUtil.getDialog(
            this,
            dialogBinding.root,
            DialogUtil.DialogGravity.CENTER
        )

        dialogBinding.tvCancel.setOnClickListener {
            dialog.dismiss()
        }

        dialogBinding.tvConfirm.setOnClickListener {
            saveData()
        }

        dialog.show()

    }


    private fun getOnProgressChangedListener(
        stringFormat: String,
        textView: TextView
    ): KBubbleSeekBar.OnProgressChangedListener {

        return object : KBubbleSeekBar.OnProgressChangedListener {
            override fun onProgressChanged(
                bubbleSeekBar: KBubbleSeekBar?,
                progress: Int,
                progressFloat: Float,
                fromUser: Boolean
            ) {
                textView.text = String.format(stringFormat, progress * 10)
            }

            override fun getProgressOnActionUp(
                bubbleSeekBar: KBubbleSeekBar?,
                progress: Int,
                progressFloat: Float
            ) {
            }

            override fun getProgressOnFinally(
                bubbleSeekBar: KBubbleSeekBar?,
                progress: Int,
                progressFloat: Float,
                fromUser: Boolean
            ) {

                viewModel.lightNightLiveData.value =
                    arrayListOf(
                        LightNightVo(
                            binding.sbLight.progress * 10,
                            binding.sbNight.progress * 10
                        )
                    )

                thread = null
                thread?.stopThread()
                thread = LightningThread(
                    applicationContext,
                    viewModel.lightNightLiveData.value,
                    viewModel.periodLiveData.value ?: 2
                )
                thread?.start()
                textView.text = String.format(stringFormat, progress * 10)
            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        thread?.stopThread()
        thread = null
    }
}